
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>	<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
   <style>
   *{padding:0px;margin:0px}
   #main{    background: silver;    width:200px;    height:200px;  }
   .dd{    width:20px;    height: 20px;    background:red;    position: absolute;  z-index:999  }
   .gift{    width:20px;    height: 20px;    background:blue;    position: absolute;   }
   </style>    
</head>
<body>
<div id="main">
<div id="dd" class="dd"></div>
</div>
<script>
var main = document.getElementById("main");

var dd= new Array();//dd为蛇数组
dd[0]= document.getElementById("dd");
var step = 20;  //移动距离
var width =200; 
var flag =40;
var gift = 0;
var gift_model ;

setInterval(function(){
    var ss1 = dd[0].offsetLeft-step;
    var ss2 = dd[0].offsetLeft+step;
    //判断是否碰到边界
    if((dd[0].offsetLeft-step)<0&&flag==37||(dd[0].offsetTop-step)<0&&flag==38||(dd[0].offsetLeft+40)>width&&flag==39||(dd[0].offsetTop+40)>width&&flag==40){
        alert("GAME OVER");
        flag=0;
    }
    //蛇格子走向
    for(var i=dd.length-1;i>=0;i--){
            if(i!=0){
                dd[i].style.left=dd[i-1].style.left
                dd[i].style.top= dd[i-1].style.top;
                tempx = dd[i]
            }
            else{
                switch(flag){
                case 0: return;
                case 37:dd[i].style.left=dd[i].offsetLeft-step+'px';break;
                case 39:dd[i].style.left=dd[i].offsetLeft+step+'px';break;
                case 38:dd[i].style.top=dd[i].offsetTop-step+'px';break;
                case 40:dd[i].style.top=dd[i].offsetTop+step+'px';break;
                }
            }        
    }    
    //碰到随机蛇则增加原蛇身体
    if(typeof gift_model =="object"&&dd[0].offsetTop==gift_model.offsetTop&&dd[0].offsetLeft==gift_model.offsetLeft){
        dd.push(gift_model);
        gift =0;
    }
    
    document.onkeydown=function(e){
	e=e||event;
	flag = e.keyCode;
	}
},500)
setInterval(function(){
	if(gift ==0){
	   creat("gift");
	}
    gift =1;
},1000)
//增加蛇身
function creat(type){
    var div = document.createElement("div");
    div.className = type;
    if(type=="gift"){
        div.style.top=Math.floor(Math.random()*10)*20+'px';
        div.style.left=Math.floor(Math.random()*10)*20+'px';
    }
    main.insertBefore(div, main.childNodes[0]);
    gift_model=div;
    gift=1;
}

</script>
</body>
</html>

